# — coding: utf-8 –
import os
import sys
import time

import Config.Params
from Utils import TimeUtil, DirUtil, IOUtil
import xlwings as xw

# from Utils.XLWingsUtil import isExcelOpen, updateXLbyCellIJ_XQ_Articles, updateXLbyCellIJ_XQ_Users, updateXLbyCellIJ
from Utils.XLWingsUtil import  *

logFileName = os.path.basename(__file__).split(".")[0]
from Statistics.COMMON import commonLogger
log = commonLogger

def recordAction(funcName,serial,args):
    fileDir = os.path.join(Config.Params.ROOT_DIR,"raw/records")
    filePath = os.path.join(fileDir,'Act_'+serial+".txt")
    timeNowStr = TimeUtil.getFormatTimeNow()
    with open(filePath,"a",encoding='utf-8',errors='ignore') as f:
        f.write(f'\n{timeNowStr}\t{funcName}\t{args[2:]}')
def recordSthInAct(sth:str,serial=None):
    if serial==None:
        serial="unknown_Serial"
    fileDir = os.path.join(Config.Params.ROOT_DIR, "raw/records")
    filePath = os.path.join(fileDir, 'Act_' + serial + ".txt")
    timeNowStr = TimeUtil.getFormatTimeNow()
    with open(filePath, "a", encoding='utf-8', errors='ignore') as f:
        f.write(f'\n{timeNowStr}\t{sth}')
def recordInfo(serial, infoList:list,infoTag="Info"):
    fileDir = os.path.join(Config.Params.ROOT_DIR,"raw/records")
    filePath = os.path.join(fileDir,infoTag+'_'+serial+".txt")
    timeNowStr = TimeUtil.getFormatTimeNow()
    with open(filePath,"a",encoding='utf-8',errors='ignore') as f:
        f.write(f'\n{timeNowStr}\t{joinToStr(infoList)}')
def joinToStr(infoList:list,sep='\t'):
    newInfoList = []
    for i in range(len(infoList)):
        newInfoList.append(str(infoList[i]))
    return sep.join(newInfoList)

def getModulePathBySrcFilePath(srcFilePath:str):
    moduleDir = os.path.join(Config.Params.ROOT_DIR,"./raw/modules")
    if srcFilePath.find("xq_articles")>=0:
        return os.path.join(moduleDir,"Module_XQ_Articles.xlsx")
    elif srcFilePath.find("xq_users")>=0:
        return os.path.join(moduleDir,"Module_XQ_Users.xlsx")
    elif srcFilePath.find("xhs_baokuan")>=0:
        return os.path.join(moduleDir,"Module_XHS_Links.xlsx")
    elif srcFilePath.find("xhs_comments")>=0:
        return os.path.join(moduleDir,"Module_XHS_Comments.xlsx")
    else:
        return None
def recordToXlsxByNaAndModule(srcFilePath:str,modulePath:str=None):
    if modulePath is None:
        modulePath = getModulePathBySrcFilePath(srcFilePath)
    fileDir, fileName = os.path.split(srcFilePath)
    srcFileNa, ex = os.path.splitext(fileName)
    app = xw.App(visible=False, add_book=False)
    if isExcelOpen(modulePath):
        print("Has open:", modulePath)
        sys.exit(0)
    wb = app.books.open(modulePath)
    t101 = time.time()
    arr = IOUtil.file2ArrArr(srcFilePath)
    t102 = time.time()
    print(f'yzprt t102-t101:{round(t102 - t101, 3)}')
    # 以下是测试操作
    if srcFilePath.find("xq_articles")>=0:
        updateXLbyCellIJ_XQ_Articles(wb, arr)
    elif srcFilePath.find("xq_users")>=0:
        updateXLbyCellIJ_XQ_Users(wb, arr)
    elif srcFilePath.find("xhs_baokuan")>=0:
        updateXLbyCellIJ_XHS_Links(wb, arr)
    elif srcFilePath.find("xq_comments")>=0:
        updateXLbyCellIJ_XHS_Comments(wb, arr)
    else:
        updateXLbyCellIJ(wb,arr)
    t103 = time.time()
    print(f'yzprt t103-t102:{round(t103 - t102, 3)}')
    wb.save(os.path.join(os.path.join(Config.Params.ROOT_DIR,"./raw/records"),srcFileNa + "_" + TimeUtil.stampS2TimeStr(TimeUtil.getStamp10(), fmt="mdHMS") + ".xlsx"))
    # wb.save()
    wb.close()
    app.quit()
    print(f'yzprt 记录并整理完成,总整理条数: {len(arr)}')
def batchRecrodTxt2Xlsx(rootDir,flagWhite=None):
    print("yzprt rootDir:", rootDir)
    for path, dirs, files in os.walk(rootDir):
        for fileName in files:
            print("yzprt fileName:", fileName)
            if not str(fileName).endswith('.txt'):
                continue
            if flagWhite is not None and str(fileName).find(flagWhite)<0:
                continue
            srcFilePath = os.path.join(path, fileName)
            print("yzprt srcFilePath@batchRecrodTxt2Xlsx:", srcFilePath)
            recordToXlsxByNaAndModule(srcFilePath)


if __name__ == '__main__':
    pass
    # recordAction("aa",22,d="d")
    # recordToXlsxByNaAndModule(srcFilePath=r"C:\Users\Administrator\Desktop\xq_articles_249cc885.txt")
    rootDir = r"%s\raw\records"%(Config.Params.ROOT_DIR)
    batchRecrodTxt2Xlsx(rootDir,flagWhite="_baokuan_")
    # batchRecrodTxt2Xlsx(rootDir, flagWhite="_comments_")